package www.my.myselector.ImgSelect;

import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.provider.MediaStore;
//import android.support.v4.app.LoaderManager;
//import android.support.v4.content.CursorLoader;
//import android.support.v4.content.Loader;
//import androidx.recyclerview.widget.GridLayoutManager;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;


import com.my.screenadapter.R;
import com.my.screenadapter.utils.Base64Util;
import com.my.screenadapter.utils.BitmapUtils;
import com.yalantis.ucrop.entity.LocalMedia;
import com.yalantis.ucrop.entity.LocalMediaFolder;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

//import www.my.myselector.main.Adapter;
//import www.my.myselector.main.GlideLoader;
//import www.my.myselector.selector.ImageConfig;
//import www.my.myselector.selector.ImageSelector;
//import www.my.myselector.selector.ImageSelectorActivity;

/**
 * Created by 张英杰 on 2016/12/7.
 *
 * 增加base64 bitmap
 */
public class MImgActivity extends AppCompatActivity {
    private RecyclerView.Adapter adapter;

    private ArrayList<String> path = new ArrayList<>();
    private final static String[] IMAGE_PROJECTION = {
            MediaStore.Images.Media.DATA,
            MediaStore.Images.Media.DISPLAY_NAME,
            MediaStore.Images.Media.DATE_ADDED,
            MediaStore.Images.Media._ID
    };
    private final static String[] VIDEO_PROJECTION = {
            MediaStore.Video.Media.DATA,
            MediaStore.Video.Media.DISPLAY_NAME,
            MediaStore.Video.Media.DATE_ADDED,
            MediaStore.Video.Media._ID,
            MediaStore.Video.Media.DURATION,
    };
    private ImageView ivShow;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_smain);
        Button viewById = (Button) findViewById(R.id.cuser);
        viewById.setText("11111");
        viewById.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                checkLocalPic();
            }

        });
        Button but = (Button) super.findViewById(www.my.myselector.R.id.but);
        RecyclerView recycler = (RecyclerView) super.findViewById(www.my.myselector.R.id.recycler);

        but.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                ImageConfig imageConfig
                        = new ImageConfig.Builder(
                        // GlideLoader 可用自己用的缓存库
                        new GlideLoader())
                        // 如果在 4.4 以上，则修改状态栏颜色 （默认黑色）
                        .steepToolBarColor(getResources().getColor(www.my.myselector.R.color.blue))
                        // 标题的背景颜色 （默认黑色）
                        .titleBgColor(getResources().getColor(www.my.myselector.R.color.blue))
                        // 提交按钮字体的颜色  （默认白色）
                        .titleSubmitTextColor(getResources().getColor(www.my.myselector.R.color.white))
                        // 标题颜色 （默认白色）
                        .titleTextColor(getResources().getColor(www.my.myselector.R.color.white))
                        // 开启多选   （默认为多选）  (单选 为 singleSelect)
//                        .singleSelect()
                        .crop()
                        // 多选时的最大数量   （默认 9 张）
                        .mutiSelectMaxSize(20)
                        // 已选择的图片路径
                        .pathList(path)
                        // 拍照后存放的图片路径（默认 /temp/picture）
//                        .filePath("/ImageSelector/Pictures")
                        .filePath("/Pictures")
                        // 开启拍照功能 （默认开启）
                        .showCamera()
                        .requestCode(REQUEST_CODE)
                        .build();

                ImageSelector.open(MImgActivity.this, imageConfig);   // 开启图片选择器
            }
        });

        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 3);
        recycler.setLayoutManager(gridLayoutManager);
        adapter = new Adapter(this, path);
        recycler.setAdapter(adapter);

        ivShow = (ImageView) findViewById(R.id.iv);
    }

    // load type
    public static final int TYPE_IMAGE = 1;
    public static final int TYPE_VIDEO = 2;
    int type=TYPE_VIDEO;
    public int index = 0;
    private void checkLocalPic() {

        MImgActivity.this.getSupportLoaderManager().initLoader(type, null, new LoaderManager.LoaderCallbacks<Cursor>() {
            @Override
            public Loader<Cursor> onCreateLoader(int id, Bundle args) {
                CursorLoader cursorLoader = null;
                if (id == TYPE_IMAGE) {
                    cursorLoader = new CursorLoader(
                            MImgActivity.this, MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                            IMAGE_PROJECTION, MediaStore.Images.Media.MIME_TYPE + "=? or "
                            + MediaStore.Images.Media.MIME_TYPE + "=?" + " or "
                            + MediaStore.Images.Media.MIME_TYPE + "=?",
                            new String[]{"image/jpeg", "image/png", "image/gif"}, IMAGE_PROJECTION[2] + " DESC");
                } else if (id == TYPE_VIDEO) {
                    cursorLoader = new CursorLoader(
                            MImgActivity.this, MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
                            VIDEO_PROJECTION, null, null, VIDEO_PROJECTION[2] + " DESC");
                }
                return cursorLoader;
            }

            @Override
            public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
                try {
                    ArrayList<LocalMediaFolder> imageFolders = new ArrayList<LocalMediaFolder>();
                    LocalMediaFolder allImageFolder = new LocalMediaFolder();
                    List<LocalMedia> allImages = new ArrayList<LocalMedia>();
                    if (data != null) {
                        int count = data.getCount();
                        if (count > 0) {
                            data.moveToFirst();
                            do {
                                String path = data.getString(data.getColumnIndexOrThrow(IMAGE_PROJECTION[0]));
                                String name = data.getString(data.getColumnIndexOrThrow(IMAGE_PROJECTION[1]));
                                // 如原图路径不存在或者路径存在但文件不存在,就结束当前循环
                                if (TextUtils.isEmpty(path) || !new File(path).exists()) {
                                    continue;
                                }
                                long dateTime = data.getLong(data.getColumnIndexOrThrow(IMAGE_PROJECTION[2]));
                                int duration = (type == TYPE_VIDEO ? data.getInt(data.getColumnIndexOrThrow(VIDEO_PROJECTION[4])) : 0);
                                LocalMedia image = new LocalMedia(path, dateTime, duration, type);
                                LocalMediaFolder folder = getImageFolder(path, imageFolders);
                                folder.getImages().add(image);
                                folder.setType(type);
                                index++;
                                folder.setImageNum(folder.getImageNum() + 1);
                                // 最近相册中  只添加最新的100条
                                if (index <= 100) {
                                    allImages.add(image);
                                    allImageFolder.setType(type);
                                    allImageFolder.setImageNum(allImageFolder.getImageNum() + 1);
                                }

                            } while (data.moveToNext());

                            if (allImages.size() > 0) {
                                sortFolder(imageFolders);
                                imageFolders.add(0, allImageFolder);
                                String title = "";
                                switch (type) {
                                    case TYPE_VIDEO:
//                                        title = activity.getStringAndShow(com.luck.picture.lib.R.string.lately_video);
                                        break;
                                    case TYPE_IMAGE:
//                                        title = activity.getStringAndShow(com.luck.picture.lib.R.string.lately_image);
                                        break;
                                }
                                allImageFolder.setFirstImagePath(allImages.get(0).getPath());
                                allImageFolder.setName(title);
                                allImageFolder.setType(type);
                                allImageFolder.setImages(allImages);
                            }
//                            imageLoadListener.loadComplete(imageFolders);
                        } else {
                            // 如果没有相册
//                            imageLoadListener.loadComplete(imageFolders);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }finally {
                    data.close();
                }
            }

            @Override
            public void onLoaderReset(Loader<Cursor> loader) {
            }
        });
    }

    private void sortFolder(List<LocalMediaFolder> imageFolders) {
        // 文件夹按图片数量排序
        Collections.sort(imageFolders, new Comparator<LocalMediaFolder>() {
            @Override
            public int compare(LocalMediaFolder lhs, LocalMediaFolder rhs) {
                if (lhs.getImages() == null || rhs.getImages() == null) {
                    return 0;
                }
                int lsize = lhs.getImageNum();
                int rsize = rhs.getImageNum();
                return lsize == rsize ? 0 : (lsize < rsize ? 1 : -1);
            }
        });
    }

    private LocalMediaFolder getImageFolder(String path, List<LocalMediaFolder> imageFolders) {
        File imageFile = new File(path);
        File folderFile = imageFile.getParentFile();
        Log.i("img====", imageFile.getName()+"  ---    "+imageFile.toString());
        for (LocalMediaFolder folder : imageFolders) {
            if (folder.getName().equals(folderFile.getName())) {
                return folder;
            }
        }
        LocalMediaFolder newFolder = new LocalMediaFolder();
        newFolder.setName(folderFile.getName());
        newFolder.setPath(folderFile.getAbsolutePath());
        newFolder.setFirstImagePath(path);
        imageFolders.add(newFolder);
        return newFolder;
    }


    public static final int REQUEST_CODE = 1000;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE && resultCode == RESULT_OK && data != null) {
            List<String> pathList = data.getStringArrayListExtra(ImageSelectorActivity.EXTRA_RESULT);

            for (String path : pathList) {
                Log.i("ImagePathList", path);
            }

            path.clear();
            path.addAll(pathList);
            adapter.notifyDataSetChanged();
        }
    }

    private static final String TAG = "MImgActivity";
    public void showBase64Bitmap(View v){

        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.hebei_1);
        String string = Base64Util.encodeBitmapToString(bitmap, 100);
        Log.i(TAG, "showBase64Bitmap: string.length()=="+string.length());
        Bitmap bitmap1 = Base64Util.decodeBase64StrToBitmap(string);
        Log.i(TAG, "showBase64Bitmap: string.length()=="+(bitmap1==null));
        if (bitmap1 != null) {
            ivShow.setImageBitmap(bitmap1);
        }
    }

    public void imgToBase64(View view) {
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.hebei_1);
        String tempFilePath = this.getCacheDir() + File.separator + "temp.jpeg";
        BitmapUtils.saveBitmapToFile(bitmap,tempFilePath);
        String s = Base64Util.encodeImgBase64(tempFilePath);
        Log.i(TAG, "imgToBase64: method1: "+s);

        String s2 = Base64Util.encodeImgBase64Two(tempFilePath);
        Log.i(TAG, "imgToBase64: method2: "+s2);

    }
}
